package com.zyg.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyg.entity.LoginUser;
import com.zyg.entity.User;
import com.zyg.mapper.UserMapper;
import com.zyg.service.UserService;
import com.zyg.utils.JwtUtil;
import com.zyg.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /**
     * 获取认证入口
     */
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Map<String, String> login(User user) {
        // 在没认证之前principal, credentials两个参数分别存放用户名和密码
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        // 通过AuthenticationManager的authenticate方法来进行用户认证，这个就是调用service层中的的方法从数据库中查询
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 判断是否验证成功
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        // 在认证信息authenticate中获取登录成功后的用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        // 使用userid生成token
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        // userId用作key，将用户信息存入redis，并设置30分钟过期
        redisCache.setCacheObject("login:" + userId, loginUser, 30, TimeUnit.MINUTES);
        // 把token响应给前端
        Map<String, String> map = new HashMap<String, String>();
        map.put("token", jwt);
        map.put("message", "登录成功");
        return map;
    }
}
